import { add_edit_role } from '@/services/role';
import authList from '@/utils/auth';
import { ActionType, ProForm, ProFormGroup, ProFormText } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Divider, Form, message, Modal, Spin, Switch, Tree } from 'antd';
import { useEffect, useState } from 'react';
interface Iprops {
  isShowAddModal: (show: boolean) => void;
  isAddModalOpen: boolean;
  actionRef: React.MutableRefObject<ActionType | undefined>;
}
type Tvalue = {
  remark: string;
  rolename: string;
  status: boolean;
};
const AddRolePermission = (props: Iprops) => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const { isShowAddModal, isAddModalOpen, actionRef } = props;
  // 存储权限列表
  const [auth, setauth] = useState<any>(undefined);
  // 存储选中的权限
  const [selectedAuth, setselectedAuth] = useState([]);
  // 选中某个权限的回调
  const onCheck = (checkedKeys: any, info: any) => {
    setselectedAuth(checkedKeys);
    console.log(checkedKeys);
  };
  // 组件初始化渲染
  useEffect(() => {
    get_auth_list();
  }, []);

  // 获取权限列表
  const get_auth_list = async () => {
    let arr = initialState?.currentUser?.current_platform.model_permissions;
    console.log('arr', arr);
    let newArr: any = [];
    authList.map((item: any) => {
      if (arr.some((i: any) => i == item.id)) {
        newArr.push(item);
      }
    });
    if (newArr.length > 0) {
      newArr.map((item: any) => {
        item.key = item.id;
        item.children?.map((item2: any) => {
          item2.key = item2.id;
        });
      });
      setauth(newArr);
    }
  };
  // console.log('JSON.stringify(selectedAuth)', JSON.stringify(selectedAuth));
  // 添加角色
  const add_role = async (value: Tvalue) => {
    if (value.status) {
      var switch_status = 1;
    } else {
      var switch_status = 0;
    }

    //组织数据
    let request_body = {
      rolename: value.rolename,
      status: switch_status,
      remark: value.remark,
      auth_ids: JSON.stringify(selectedAuth),
    };
    //提交
    let res: any = await add_edit_role(request_body);
    // console.log('新增角色', res);
    if (res.msg == 'ok') {
      //刷新列表
      actionRef.current?.reload();
      message.success('添加成功');
      //关闭弹窗
      isShowAddModal(false);
    } else {
      message.error(res.msg);
    }
  };
  return (
    <Modal
      title="新增角色"
      centered
      open={isAddModalOpen}
      onCancel={() => isShowAddModal(false)}
      width={700}
      destroyOnClose={true}
      footer={null}
    >
      <Divider />
      <ProForm<{
        rolename: string;
        status: boolean;
        remark: string;
      }>
        onReset={() => isShowAddModal(false)}
        onFinish={(value) => add_role(value)}
        submitter={{
          searchConfig: {
            submitText: '提交',
            resetText: '返回',
          },
          resetButtonProps: {
            style: {
              // 隐藏重置按钮
              display: 'block',
              position: 'absolute',
              left: 'calc(50% - 107px)',
            },
          },
          submitButtonProps: {
            style: {
              display: 'block',
              position: 'absolute',
              right: 'calc(50% - 107px)',
            },
          },
        }}
      >
        <div style={{ display: 'flex' }}>
          <div style={{ flex: '1' }}>
            <ProFormGroup>
              <ProFormText
                width={250}
                name="rolename"
                label="角色名称"
                placeholder="请输入角色名称"
                rules={[
                  {
                    required: true,
                    message: '请输入角色名称',
                    validateTrigger: 'onBlur',
                  },
                  { pattern: /(^\S)((.)*\S)?(\S*$)/, message: '不能输入空格' },
                ]}
              />
              <Form.Item name="status" label="状态" valuePropName="checked" initialValue={true}>
                <Switch checkedChildren="启用" unCheckedChildren="禁用" defaultChecked={true} />
              </Form.Item>
              <ProFormText width={340} name="remark" label="备注" placeholder="请输入备注信息" />
            </ProFormGroup>
          </div>
          <div style={{ flex: '1', marginLeft: '30px' }}>
            <Form.Item name="auth" label="权限" valuePropName="checked">
              {auth === undefined ? (
                <div
                  style={{
                    margin: '20px 0',
                    marginBottom: '20px',
                    padding: '30px 50px',
                    textAlign: 'center',
                  }}
                >
                  <Spin size="large" />
                </div>
              ) : (
                <Tree
                  checkable
                  defaultExpandAll={true}
                  selectable={false}
                  onCheck={onCheck}
                  treeData={auth}
                />
              )}
            </Form.Item>
          </div>
        </div>
        <br />
      </ProForm>
      <br />
    </Modal>
  );
};
export default AddRolePermission;
